<template>
  <view class="survival-container">
    <!-- 顶部状态栏 -->
    <GameHeader 
      :dayNumber="1"
      @navigate-to-index="navigateToIndex"
      @open-save-manager="openSaveManager"
      @show-game-menu="showGameMenu"
    />
    
    <!-- 游戏状态指标 -->
    <GameStatusBar :gameState="gameState" />
    
    <!-- 主游戏区域 -->
    <main class="main-game-area">
      <!-- 游戏场景显示区 -->
      <GameSceneArea 
        :gameState="gameState"
        :mapTiles="mapTiles"
        :availableActions="availableActions"
        @perform-action="performAction"
      />
      
    </main>
    
    
    <!-- 底部TabBar -->
    <GameTabBar 
      :currentPage="currentPage"
      @switch-tab="switchTab"
      @open-map-modal="openMapModal"
      @open-inventory-modal="openInventoryModal"
      @open-buildings-modal="openBuildingsModal"
      @open-tech-modal="openTechModal"
      @open-settings-modal="openSettingsModal"
    />
    
    <!-- 地图弹窗 -->
    <GameModal 
      :visible="showMapModal" 
      title="🗺️ 地图探索"
      @close="closeMapModal"
    >
      <SurvivalPage
        ref="survivalPage"
        :gameState="gameState"
        :gameLog="gameLog"
        :showSaveManager="showSaveManager"
        :saveSlots="saveSlots"
        :autoSave="autoSave"
        :availableActions="availableActions"
        :explorationPoints="explorationPoints"
        :mapTiles="mapTiles"
        :currentLocationId="gameState.currentLocationId"
        @perform-action="performAction"
        @close-save-manager="closeSaveManager"
        @save-to-slot="saveToSlot"
        @load-from-slot="loadFromSlot"
        @load-auto-save="loadAutoSave"
        @explore-tile="exploreTile"
        @switch-location="switchLocation"
      />
    </GameModal>
    
    <!-- 背包弹窗 -->
    <GameModal 
      :visible="showInventoryModal" 
      title="🎒 背包管理"
      @close="closeInventoryModal"
    >
      <InventoryPage
        :inventory="inventory"
        :maxSlots="maxSlots"
        :currentFilter="currentFilter"
        :selectedItem="selectedItem"
        :selectedItemInfo="selectedItemInfo"
        @set-filter="setFilter"
        @select-item="selectItem"
        @use-item="useItem"
        @drop-item="dropItem"
      />
    </GameModal>
    
    <!-- 建筑弹窗 -->
    <GameModal 
      :visible="showBuildingsModal" 
      title="🏗️ 建筑管理"
      @close="closeBuildingsModal"
    >
      <BuildingsPage
        :buildings="buildings"
        :currentCategory="currentCategory"
        :selectedBuilding="selectedBuilding"
        :selectedBuildingInfo="selectedBuildingInfo"
        @set-category="setCategory"
        @select-building="selectBuilding"
        @build-building="buildBuilding"
        @upgrade-building="upgradeBuilding"
      />
    </GameModal>
    
    <!-- 科技弹窗 -->
    <GameModal 
      :visible="showTechModal" 
      title="🔬 科技研究"
      @close="closeTechModal"
    >
      <TechPage
        :techs="techs"
        :researchPoints="researchPoints"
        :researchSpeed="researchSpeed"
        :techCategory="techCategory"
        :selectedTech="selectedTech"
        :selectedTechInfo="selectedTechInfo"
        @set-tech-category="setTechCategory"
        @select-tech="selectTech"
        @start-research="startResearch"
        @cancel-research="cancelResearch"
      />
    </GameModal>
    
    <!-- 设置弹窗 -->
    <GameModal 
      :visible="showSettingsModal" 
      title="⚙️ 游戏设置"
      @close="closeSettingsModal"
    >
      <GameSettingsPage
        :gameSettings="gameSettings"
        :showAudioSettings="showAudioSettings"
        :showDisplaySettings="showDisplaySettings"
        :showDataSettings="showDataSettings"
        :showHelpSettings="showHelpSettings"
        @toggle-audio-settings="toggleAudioSettings"
        @toggle-display-settings="toggleDisplaySettings"
        @toggle-data-settings="toggleDataSettings"
        @toggle-help-settings="toggleHelpSettings"
        @toggle-sound="toggleSound"
        @toggle-music="toggleMusic"
        @toggle-vibration="toggleVibration"
        @toggle-dark-mode="toggleDarkMode"
        @toggle-animations="toggleAnimations"
        @select-difficulty="selectDifficulty"
        @show-game-stats="showGameStats"
        @backup-game-data="backupGameData"
        @restore-game-data="restoreGameData"
        @reset-game-data="resetGameData"
        @show-game-help="showGameHelp"
        @show-game-controls="showGameControls"
        @show-about-game="showAboutGame"
      />
    </GameModal>
  </view>
</template>

<script>
import SurvivalPage from './components/SurvivalPage.vue'
import InventoryPage from './components/InventoryPage.vue'
import BuildingsPage from './components/BuildingsPage.vue'
import TechPage from './components/TechPage.vue'
import GameSettingsPage from './components/GameSettingsPage.vue'
import GameTabBar from './components/GameTabBar.vue'
import GameHeader from './components/GameHeader.vue'
import GameStatusBar from './components/GameStatusBar.vue'
import GameSceneArea from './components/GameSceneArea.vue'
import GameModal from './components/GameModal.vue'

export default {
  name: 'SurvivalGame',
  components: {
    SurvivalPage,
    InventoryPage,
    BuildingsPage,
    TechPage,
    GameSettingsPage,
    GameTabBar,
    GameHeader,
    GameStatusBar,
    GameSceneArea,
    GameModal
  },
  
  data() {
    return {
      gameState: {
        health: 100,
        hunger: 100,
        thirst: 100,
        energy: 100,
        currentLocation: '海滩',
        currentLocationId: 'beach',
        resources: {
          wood: 0,
          stone: 0,
          food: 0,
          water: 0
        }
      },
      gameLog: [],
      gameTimer: null,
      showSaveManager: false,
      currentPage: 'survival', // 当前页面标识
      showSidebar: false, // 控制侧边栏显示/隐藏
      
      // 弹窗状态管理
      showMapModal: false,
      showInventoryModal: false,
      showBuildingsModal: false,
      showTechModal: false,
      showSettingsModal: false,
      saveSlots: [
        { time: null, data: null },
        { time: null, data: null },
        { time: null, data: null }
      ],
      autoSave: { time: null, data: null },
      
      // 地图探索数据
      explorationPoints: 10,
      mapTiles: [
        {
          id: 'beach',
          name: '海滩',
          icon: '🏖️',
          description: '一片开阔的海滩，可以看到远处的大海。这里有一些漂来的木材和贝壳。',
          explored: true,
          discovered: true,
          resources: ['wood', 'shells'],
          actions: ['gatherWood', 'findShells', 'rest'],
          position: { x: 150, y: 300 }
        },
        {
          id: 'forest',
          name: '森林',
          icon: '🌲',
          description: '茂密的森林，树木参天。这里有丰富的木材和可能的食物。',
          explored: false,
          discovered: false,
          resources: ['wood', 'food', 'berries'],
          actions: ['gatherWood', 'findFood', 'gatherBerries'],
          position: { x: 300, y: 200 }
        },
        {
          id: 'cave',
          name: '山洞',
          icon: '🕳️',
          description: '一个阴暗的山洞，里面有石头和可能的庇护所。',
          explored: false,
          discovered: false,
          resources: ['stone', 'crystals'],
          actions: ['gatherStone', 'findCrystals', 'shelter'],
          position: { x: 450, y: 250 }
        },
        {
          id: 'river',
          name: '河流',
          icon: '🏞️',
          description: '清澈的河流，是获取淡水的理想地点。',
          explored: false,
          discovered: false,
          resources: ['water', 'fish'],
          actions: ['collectWater', 'catchFish'],
          position: { x: 200, y: 400 }
        },
        {
          id: 'mountain',
          name: '山峰',
          icon: '⛰️',
          description: '高耸的山峰，可以俯瞰整个岛屿。',
          explored: false,
          discovered: false,
          resources: ['stone', 'metal'],
          actions: ['gatherStone', 'findMetal', 'scout'],
          position: { x: 350, y: 150 }
        },
        {
          id: 'ruins',
          name: '遗迹',
          icon: '🏛️',
          description: '古老的遗迹，可能隐藏着宝藏和秘密。',
          explored: false,
          discovered: false,
          resources: ['treasure', 'artifacts'],
          actions: ['exploreRuins', 'findTreasure'],
          position: { x: 600, y: 350 }
        },
        {
          id: 'volcano',
          name: '火山',
          icon: '🌋',
          description: '活跃的火山，危险但富含稀有矿物。',
          explored: false,
          discovered: false,
          resources: ['obsidian', 'sulfur'],
          actions: ['gatherObsidian', 'collectSulfur'],
          position: { x: 750, y: 200 }
        },
        {
          id: 'lake',
          name: '湖泊',
          icon: '🏞️',
          description: '宁静的湖泊，周围有丰富的植物资源。',
          explored: false,
          discovered: false,
          resources: ['water', 'reeds', 'clay'],
          actions: ['collectWater', 'gatherReeds', 'collectClay'],
          position: { x: 180, y: 500 }
        },
        {
          id: 'desert',
          name: '沙漠',
          icon: '🏜️',
          description: '广阔的沙漠，隐藏着古老的秘密。',
          explored: false,
          discovered: false,
          resources: ['sand', 'cactus', 'fossils'],
          actions: ['collectSand', 'harvestCactus', 'findFossils'],
          position: { x: 900, y: 400 }
        },
        {
          id: 'swamp',
          name: '沼泽',
          icon: '🐸',
          description: '潮湿的沼泽地，有独特的生物和资源。',
          explored: false,
          discovered: false,
          resources: ['mud', 'mushrooms', 'frogs'],
          actions: ['collectMud', 'gatherMushrooms', 'catchFrogs'],
          position: { x: 80, y: 600 }
        },
        {
          id: 'cliff',
          name: '悬崖',
          icon: '⛰️',
          description: '陡峭的悬崖，可以找到珍贵的矿物。',
          explored: false,
          discovered: false,
          resources: ['iron', 'gold', 'gems'],
          actions: ['mineIron', 'mineGold', 'findGems'],
          position: { x: 1000, y: 250 }
        },
        {
          id: 'meadow',
          name: '草地',
          icon: '🌾',
          description: '开阔的草地，适合种植和放牧。',
          explored: false,
          discovered: false,
          resources: ['grass', 'seeds', 'herbs'],
          actions: ['gatherGrass', 'collectSeeds', 'harvestHerbs'],
          position: { x: 350, y: 450 }
        },
        {
          id: 'island',
          name: '小岛',
          icon: '🏝️',
          description: '海中的小岛，可能有独特的资源。',
          explored: false,
          discovered: false,
          resources: ['coral', 'pearls', 'seaweed'],
          actions: ['collectCoral', 'findPearls', 'gatherSeaweed'],
          position: { x: 50, y: 150 }
        },
        {
          id: 'glacier',
          name: '冰川',
          icon: '🧊',
          description: '寒冷的冰川，有纯净的冰和水。',
          explored: false,
          discovered: false,
          resources: ['ice', 'crystal', 'frozen_fish'],
          actions: ['collectIce', 'findCrystal', 'catchFrozenFish'],
          position: { x: 1100, y: 100 }
        },
        {
          id: 'oasis',
          name: '绿洲',
          icon: '🌴',
          description: '沙漠中的绿洲，生命的天堂。',
          explored: false,
          discovered: false,
          resources: ['dates', 'palm_fiber', 'fresh_water'],
          actions: ['harvestDates', 'collectPalmFiber', 'collectFreshWater'],
          position: { x: 850, y: 500 }
        }
      ],
      
      // 背包页面数据
      currentFilter: 'all',
      selectedItem: null,
      selectedItemInfo: null,
      maxSlots: 20,
      inventory: [
        { id: 1, name: '木材', icon: '🌲', type: 'resources', count: 10, value: 5, description: '基础建筑材料' },
        { id: 2, name: '石头', icon: '🪨', type: 'resources', count: 5, value: 8, description: '坚固的建筑材料' },
        { id: 3, name: '苹果', icon: '🍎', type: 'food', count: 3, value: 3, description: '恢复饥饿值' },
        { id: 4, name: '水', icon: '💧', type: 'food', count: 2, value: 2, description: '恢复口渴值' },
        { id: 5, name: '斧头', icon: '🪓', type: 'tools', count: 1, value: 50, description: '提高木材收集效率' }
      ],
      
      // 建筑页面数据
      currentCategory: 'all',
      selectedBuilding: null,
      selectedBuildingInfo: null,
      buildings: [
        {
          id: 'house',
          name: '木屋',
          icon: '🏠',
          category: 'utility',
          description: '提供休息和存储空间',
          built: false,
          level: 1,
          cost: '木材: 20',
          production: '休息效率 +50%',
          requirements: [
            { type: '木材', amount: 20 }
          ]
        },
        {
          id: 'workshop',
          name: '工作台',
          icon: '🔨',
          category: 'production',
          description: '制作工具和物品',
          built: false,
          level: 1,
          cost: '木材: 15, 石头: 10',
          production: '制作效率 +100%',
          requirements: [
            { type: '木材', amount: 15 },
            { type: '石头', amount: 10 }
          ]
        }
      ],
      
      // 科技页面数据
      techCategory: 'all',
      selectedTech: null,
      selectedTechInfo: null,
      researchPoints: 100,
      researchSpeed: 10,
      techs: [
        {
          id: 'basic_tools',
          name: '基础工具',
          icon: '🔧',
          category: 'production',
          description: '解锁基础工具制作',
          level: 1,
          cost: '研究点: 50',
          time: '1小时',
          available: true,
          researching: false,
          completed: false,
          locked: false,
          effects: [
            { type: '制作效率', value: '+20%' }
          ],
          requirements: []
        }
      ],
      
      // 游戏设置页面数据
      showAudioSettings: false,
      showDisplaySettings: false,
      showDataSettings: false,
      showHelpSettings: false,
      gameSettings: {
        soundEnabled: true,
        musicEnabled: true,
        vibrationEnabled: true,
        darkMode: false,
        difficulty: 'normal',
        animationsEnabled: true
      },
      availableActions: [
        {
          id: 'gather_wood',
          name: '收集木材',
          icon: '🌲',
          cost: '精力: 10',
          action: 'gatherWood'
        },
        {
          id: 'gather_stone',
          name: '收集石头',
          icon: '🪨',
          cost: '精力: 15',
          action: 'gatherStone'
        },
        {
          id: 'find_food',
          name: '寻找食物',
          icon: '🍎',
          cost: '精力: 20',
          action: 'findFood'
        },
        {
          id: 'find_water',
          name: '寻找水源',
          icon: '💧',
          cost: '精力: 15',
          action: 'findWater'
        },
        {
          id: 'rest',
          name: '休息',
          icon: '😴',
          cost: '时间',
          action: 'rest'
        }
      ]
    }
  },
  
  computed: {
    healthPercent() {
      return this.gameState?.health || 0
    },
    hungerPercent() {
      return this.gameState?.hunger || 0
    },
    thirstPercent() {
      return this.gameState?.thirst || 0
    },
    energyPercent() {
      return this.gameState?.energy || 0
    },
    locationDescription() {
      const descriptions = {
        '海滩': '一片开阔的海滩，可以看到远处的大海。这里有一些漂来的木材和贝壳。',
        '森林': '茂密的森林，树木参天。这里有丰富的木材和可能的食物。',
        '山洞': '一个阴暗的山洞，里面有石头和可能的庇护所。'
      }
      return descriptions[this.gameState?.currentLocation] || '未知区域'
    },
    filteredItems() {
      if (this.currentFilter === 'all') {
        return this.inventory
      }
      return this.inventory.filter(item => item.type === this.currentFilter)
    },
    totalItems() {
      return this.inventory.reduce((total, item) => total + item.count, 0)
    },
    usedSlots() {
      return this.inventory.length
    },
    emptySlots() {
      return this.maxSlots - this.usedSlots
    },
    inventoryValue() {
      return this.inventory.reduce((total, item) => total + (item.value * item.count), 0)
    },
    filteredBuildings() {
      if (this.currentCategory === 'all') {
        return this.buildings
      }
      return this.buildings.filter(building => building.category === this.currentCategory)
    },
    builtBuildings() {
      return this.buildings.filter(building => building.built).length
    },
    totalPopulation() {
      return this.buildings.reduce((total, building) => {
        return building.built ? total + (building.population || 0) : total
      }, 0)
    },
    totalProduction() {
      return this.buildings.reduce((total, building) => {
        return building.built ? total + (building.productionValue || 0) : total
      }, 0)
    },
    filteredTechs() {
      if (this.techCategory === 'all') {
        return this.techs
      }
      return this.techs.filter(tech => tech.category === this.techCategory)
    }
  },
  
  onLoad() {
    this.loadGame()
    this.startGameTimer()
  },
  
  onUnload() {
    this.stopGameTimer()
    // 自动保存游戏数据
    this.saveGameData()
  },
  
  methods: {
    // 页面切换方法
    switchTab(page) {
      this.currentPage = page
    },
    
    navigateToIndex() {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    },
    
    showGameMenu() {
      uni.showActionSheet({
        itemList: ['重置游戏', '游戏帮助', '关于游戏'],
        success: (res) => {
          switch(res.tapIndex) {
            case 0:
              this.resetGame()
              break
            case 1:
              this.showGameHelp()
              break
            case 2:
              this.showAboutGame()
              break
          }
        }
      })
    },
    
    openMapModal() {
      this.showMapModal = true
    },
    
    closeMapModal() {
      this.showMapModal = false
    },
    
    openInventoryModal() {
      this.showInventoryModal = true
    },
    
    closeInventoryModal() {
      this.showInventoryModal = false
    },
    
    openBuildingsModal() {
      this.showBuildingsModal = true
    },
    
    closeBuildingsModal() {
      this.showBuildingsModal = false
    },
    
    openTechModal() {
      this.showTechModal = true
    },
    
    closeTechModal() {
      this.showTechModal = false
    },
    
    openSettingsModal() {
      this.showSettingsModal = true
    },
    
    closeSettingsModal() {
      this.showSettingsModal = false
    },
    
    
    
    
    startGameTimer() {
      this.gameTimer = setInterval(() => {
        this.gameTick()
      }, 3000) // 每3秒执行一次游戏逻辑
    },
    
    stopGameTimer() {
      if (this.gameTimer) {
        clearInterval(this.gameTimer)
        this.gameTimer = null
      }
    },
    
    gameTick() {
      // 确保gameState已初始化
      if (!this.gameState) return
      
      // 饥饿值减少
      if (this.gameState.hunger > 0) {
        this.gameState.hunger = Math.max(0, this.gameState.hunger - 2)
      }
      
      // 口渴值减少
      if (this.gameState.thirst > 0) {
        this.gameState.thirst = Math.max(0, this.gameState.thirst - 3)
      }
      
      // 精力值恢复
      if (this.gameState.energy < 100) {
        this.gameState.energy = Math.min(100, this.gameState.energy + 1)
      }
      
      // 如果饥饿或口渴为0，生命值减少
      if (this.gameState.hunger === 0 || this.gameState.thirst === 0) {
        this.gameState.health = Math.max(0, this.gameState.health - 1)
      }
      
      // 检查游戏结束
      if (this.gameState.health === 0) {
        this.gameOver()
      }
    },
    
    performAction(action) {
      switch (action.action) {
        case 'gatherWood':
          this.gatherWood()
          break
        case 'gatherStone':
          this.gatherStone()
          break
        case 'findFood':
          this.findFood()
          break
        case 'findWater':
          this.findWater()
          break
        case 'rest':
          this.rest()
          break
      }
    },
    
    gatherWood() {
      if (this.gameState.energy >= 10) {
        this.gameState.energy -= 10
        this.gameState.resources.wood += Math.floor(Math.random() * 3) + 1
        this.addLog('收集了一些木材')
      }
    },
    
    gatherStone() {
      if (this.gameState.energy >= 15) {
        this.gameState.energy -= 15
        this.gameState.resources.stone += Math.floor(Math.random() * 2) + 1
        this.addLog('收集了一些石头')
      }
    },
    
    findFood() {
      if (this.gameState.energy >= 20) {
        this.gameState.energy -= 20
        const foodFound = Math.floor(Math.random() * 2) + 1
        this.gameState.resources.food += foodFound
        this.addLog(`找到了 ${foodFound} 个食物`)
      }
    },
    
    findWater() {
      if (this.gameState.energy >= 15) {
        this.gameState.energy -= 15
        const waterFound = Math.floor(Math.random() * 3) + 1
        this.gameState.resources.water += waterFound
        this.addLog(`找到了 ${waterFound} 单位的水`)
      }
    },
    
    rest() {
      this.gameState.energy = Math.min(100, this.gameState.energy + 30)
      this.addLog('休息了一会，恢复了精力')
    },
    
    addLog(text) {
      // 改为提示方式显示日志信息
      uni.showToast({
        title: text,
        icon: 'none',
        duration: 2000
      })
      
      // 仍然保存到gameLog用于存档
      const now = new Date()
      const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
      this.gameLog.unshift({
        time,
        text
      })
      
      // 限制日志数量
      if (this.gameLog.length > 10) {
        this.gameLog = this.gameLog.slice(0, 10)
      }
    },
    
    gameOver() {
      uni.showModal({
        title: '游戏结束',
        content: '你的生命值归零，游戏结束！',
        showCancel: false,
        success: () => {
          this.resetGame()
        }
      })
    },
    
    resetGame() {
      uni.showModal({
        title: '重置游戏',
        content: '确定要重置游戏吗？所有进度将丢失！',
        success: (res) => {
          if (res.confirm) {
            this.gameState = {
              health: 100,
              hunger: 100,
              thirst: 100,
              energy: 100,
              currentLocation: '海滩',
              currentLocationId: 'beach',
              resources: {
                wood: 0,
                stone: 0,
                food: 0,
                water: 0
              }
            }
            this.gameLog = []
            this.explorationPoints = 10
            // 重置地图探索状态
            this.mapTiles.forEach(tile => {
              tile.explored = tile.id === 'beach'
              tile.discovered = tile.id === 'beach'
            })
            // 重置背包
            this.inventory = [
              { id: 1, name: '木材', icon: '🌲', type: 'resources', count: 10, value: 5, description: '基础建筑材料' },
              { id: 2, name: '石头', icon: '🪨', type: 'resources', count: 5, value: 8, description: '坚固的建筑材料' },
              { id: 3, name: '苹果', icon: '🍎', type: 'food', count: 3, value: 3, description: '恢复饥饿值' },
              { id: 4, name: '水', icon: '💧', type: 'food', count: 2, value: 2, description: '恢复口渴值' },
              { id: 5, name: '斧头', icon: '🪓', type: 'tools', count: 1, value: 50, description: '提高木材收集效率' }
            ]
            // 重置建筑
            this.buildings.forEach(building => {
              building.built = false
              building.level = 1
            })
            // 重置科技
            this.techs.forEach(tech => {
              tech.researching = false
              tech.completed = false
            })
            this.researchPoints = 100
            uni.removeStorageSync('survival_game_data')
            this.addLog('游戏已重置')
          }
        }
      })
    },
    
    exploreTile(tile) {
      if (tile.id === this.gameState.currentLocationId) {
        uni.showToast({
          title: '你已经在当前位置',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      if (!tile.discovered) {
        // 发现新区域
        if (this.explorationPoints >= 5) {
          tile.discovered = true
          this.explorationPoints -= 5
          uni.showToast({
            title: `发现了新区域：${tile.name}`,
            icon: 'success',
            duration: 2000
          })
          this.addLog(`发现了新区域：${tile.name}`)
        } else {
          uni.showToast({
            title: '探索点数不足',
            icon: 'none',
            duration: 2000
          })
        }
        return
      }
      
      if (!tile.explored) {
        // 首次探索区域
        if (this.explorationPoints >= 3) {
          tile.explored = true
          this.explorationPoints -= 3
          this.explorationPoints += 2 // 探索奖励
          uni.showToast({
            title: `探索了区域：${tile.name}`,
            icon: 'success',
            duration: 2000
          })
          this.addLog(`探索了区域：${tile.name}`)
        } else {
          uni.showToast({
            title: '探索点数不足',
            icon: 'none',
            duration: 2000
          })
        }
        return
      }
      
      // 移动到已探索的区域
      if (this.gameState.energy >= 20) {
        this.gameState.currentLocationId = tile.id
        this.gameState.currentLocation = tile.name
        this.gameState.energy -= 20
        uni.showToast({
          title: `移动到：${tile.name}`,
          icon: 'success',
          duration: 2000
        })
        this.addLog(`移动到：${tile.name}`)
      } else {
        uni.showToast({
          title: '精力不足，无法移动',
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    switchLocation(tile) {
      // 消耗精力移动到该区域
      if (this.gameState.energy < 20) {
        uni.showToast({
          title: '精力不足，无法移动',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      this.gameState.energy -= 20
      this.gameState.currentLocation = tile.name
      this.gameState.currentLocationId = tile.id
      this.addLog(`快速移动到了 ${tile.name}`)
    },
    
    saveGameData() {
      // 保存游戏数据到本地存储
      const gameData = {
        gameState: this.gameState,
        gameLog: this.gameLog,
        timestamp: new Date().toISOString()
      }
      
      try {
        uni.setStorageSync('survival_game_data', JSON.stringify(gameData))
        // 更新自动保存
        this.autoSave = {
          time: new Date().toLocaleString(),
          data: gameData
        }
        console.log('游戏数据已保存')
      } catch (error) {
        console.error('保存游戏数据失败:', error)
      }
    },
    
    loadGame() {
      try {
        const gameData = uni.getStorageSync('survival_game_data')
        if (gameData) {
          const data = JSON.parse(gameData)
          this.gameState = { ...data.gameState }
          this.gameLog = [...data.gameLog]
          this.autoSave = {
            time: new Date(data.timestamp).toLocaleString(),
            data: data
          }
        }
      } catch (error) {
        console.log('没有找到保存的游戏数据')
      }
    },
    
    openSaveManager() {
      this.loadSaveSlots()
      this.showSaveManager = true
    },
    
    closeSaveManager() {
      this.showSaveManager = false
    },
    
    loadSaveSlots() {
      // 从本地存储加载存档槽位
      try {
        for (let i = 0; i < this.saveSlots.length; i++) {
          const slotData = uni.getStorageSync(`survival_save_slot_${i}`)
          if (slotData) {
            const data = JSON.parse(slotData)
            this.saveSlots[i] = {
              time: new Date(data.timestamp).toLocaleString(),
              data: data
            }
          }
        }
      } catch (error) {
        console.error('加载存档槽位失败:', error)
      }
    },
    
    saveToSlot(index) {
      const gameData = {
        gameState: this.gameState,
        gameLog: this.gameLog,
        timestamp: new Date().toISOString()
      }
      
      try {
        uni.setStorageSync(`survival_save_slot_${index}`, JSON.stringify(gameData))
        this.saveSlots[index] = {
          time: new Date().toLocaleString(),
          data: gameData
        }
        uni.showToast({ title: '已保存到槽位', icon: 'success', duration: 2000 })
      } catch (error) {
        uni.showToast({ title: '保存失败', icon: 'error', duration: 2000 })
      }
    },
    
    loadFromSlot(index) {
      const slot = this.saveSlots[index]
      if (!slot.data) {
        uni.showToast({ title: '槽位为空', icon: 'none', duration: 2000 })
        return
      }
      
      const data = slot.data
      this.gameState = { ...data.gameState }
      this.gameLog = [...data.gameLog]
      uni.showToast({ title: '已加载存档', icon: 'success', duration: 2000 })
      this.closeSaveManager()
    },
    
    loadAutoSave() {
      if (!this.autoSave.data) {
        uni.showToast({ title: '无自动保存数据', icon: 'none', duration: 2000 })
        return
      }
      
      const data = this.autoSave.data
      this.gameState = { ...data.gameState }
      this.gameLog = [...data.gameLog]
      uni.showToast({ title: '已加载自动保存', icon: 'success', duration: 2000 })
      this.closeSaveManager()
    },
    
    // 背包页面方法
    setFilter(filter) {
      this.currentFilter = filter
    },
    
    selectItem(item, index) {
      this.selectedItem = this.selectedItem === index ? null : index
      this.selectedItemInfo = this.selectedItem !== null ? item : null
    },
    
    useItem(item) {
      uni.showToast({
        title: `使用了${item.name}`,
        icon: 'success'
      })
      // 这里可以添加使用物品的逻辑
    },
    
    dropItem(item, index) {
      uni.showModal({
        title: '确认丢弃',
        content: `确定要丢弃${item.name}吗？`,
        success: (res) => {
          if (res.confirm) {
            this.inventory.splice(index, 1)
            this.selectedItem = null
            this.selectedItemInfo = null
            uni.showToast({
              title: '已丢弃',
              icon: 'success'
            })
          }
        }
      })
    },
    
    // 建筑页面方法
    setCategory(category) {
      this.currentCategory = category
    },
    
    selectBuilding(building) {
      this.selectedBuilding = this.selectedBuilding === building.id ? null : building.id
      this.selectedBuildingInfo = this.selectedBuilding !== null ? building : null
    },
    
    buildBuilding(building) {
      if (this.canBuild(building)) {
        building.built = true
        uni.showToast({
          title: `已建造${building.name}`,
          icon: 'success'
        })
      }
    },
    
    canBuild(building) {
      // 检查是否有足够的资源建造
      return true // 简化版本
    },
    
    upgradeBuilding(building) {
      if (this.canUpgrade(building)) {
        building.level++
        uni.showToast({
          title: `${building.name}已升级到等级${building.level}`,
          icon: 'success'
        })
      }
    },
    
    canUpgrade(building) {
      return building.built && building.level < 3
    },
    
    // 科技页面方法
    setTechCategory(category) {
      this.techCategory = category
    },
    
    selectTech(tech) {
      this.selectedTech = this.selectedTech === tech.id ? null : tech.id
      this.selectedTechInfo = this.selectedTech !== null ? tech : null
    },
    
    startResearch(tech) {
      if (this.canResearch(tech)) {
        tech.researching = true
        this.researchPoints -= 50
        uni.showToast({
          title: `开始研究${tech.name}`,
          icon: 'success'
        })
        
        // 模拟研究完成
        setTimeout(() => {
          tech.researching = false
          tech.completed = true
          uni.showToast({
            title: `${tech.name}研究完成`,
            icon: 'success'
          })
        }, 5000)
      }
    },
    
    canResearch(tech) {
      return tech.available && this.researchPoints >= 50
    },
    
    cancelResearch(tech) {
      tech.researching = false
      this.researchPoints += 50
      uni.showToast({
        title: `取消研究${tech.name}`,
        icon: 'none'
      })
    },
    
    // 游戏设置页面方法
    toggleAudioSettings() {
      this.showAudioSettings = !this.showAudioSettings
    },
    
    toggleDisplaySettings() {
      this.showDisplaySettings = !this.showDisplaySettings
    },
    
    toggleDataSettings() {
      this.showDataSettings = !this.showDataSettings
    },
    
    toggleHelpSettings() {
      this.showHelpSettings = !this.showHelpSettings
    },
    
    toggleSound(e) {
      this.gameSettings.soundEnabled = e.detail.value
      uni.showToast({
        title: this.gameSettings.soundEnabled ? '音效已开启' : '音效已关闭',
        icon: 'none',
        duration: 1500
      })
    },
    
    toggleMusic(e) {
      this.gameSettings.musicEnabled = e.detail.value
      uni.showToast({
        title: this.gameSettings.musicEnabled ? '背景音乐已开启' : '背景音乐已关闭',
        icon: 'none',
        duration: 1500
      })
    },
    
    toggleVibration(e) {
      this.gameSettings.vibrationEnabled = e.detail.value
      uni.showToast({
        title: this.gameSettings.vibrationEnabled ? '震动反馈已开启' : '震动反馈已关闭',
        icon: 'none',
        duration: 1500
      })
    },
    
    toggleDarkMode(e) {
      this.gameSettings.darkMode = e.detail.value
      uni.showToast({
        title: this.gameSettings.darkMode ? '深色模式已开启' : '深色模式已关闭',
        icon: 'none',
        duration: 1500
      })
    },
    
    toggleAnimations(e) {
      this.gameSettings.animationsEnabled = e.detail.value
      uni.showToast({
        title: this.gameSettings.animationsEnabled ? '动画效果已开启' : '动画效果已关闭',
        icon: 'none',
        duration: 1500
      })
    },
    
    selectDifficulty() {
      const difficulties = [
        { value: 'easy', text: '简单' },
        { value: 'normal', text: '普通' },
        { value: 'hard', text: '困难' }
      ]
      
      uni.showActionSheet({
        itemList: difficulties.map(d => d.text),
        success: (res) => {
          this.gameSettings.difficulty = difficulties[res.tapIndex].value
          uni.showToast({
            title: `难度已设置为${difficulties[res.tapIndex].text}`,
            icon: 'success',
            duration: 2000
          })
        }
      })
    },
    
    getDifficultyText(difficulty) {
      const difficultyMap = {
        'easy': '简单',
        'normal': '普通',
        'hard': '困难'
      }
      return difficultyMap[difficulty] || '普通'
    },
    
    showGameStats() {
      uni.showModal({
        title: '游戏统计',
        content: `总游戏时间: 2小时30分钟\n生存天数: 15天\n收集资源: 500个\n建造建筑: 8个`,
        showCancel: false
      })
    },
    
    backupGameData() {
      uni.showToast({
        title: '游戏数据已备份',
        icon: 'success'
      })
    },
    
    restoreGameData() {
      uni.showModal({
        title: '恢复存档',
        content: '确定要恢复备份的存档吗？当前进度将被覆盖。',
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '存档已恢复',
              icon: 'success'
            })
          }
        }
      })
    },
    
    resetGameData() {
      uni.showModal({
        title: '重置荒岛生存',
        content: '确定要重置荒岛生存游戏的所有数据吗？此操作不可撤销！',
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '荒岛生存数据已重置',
              icon: 'success',
              duration: 2000
            })
          }
        }
      })
    },
    
    showGameHelp() {
      uni.showModal({
        title: '游戏帮助',
        content: '欢迎来到荒岛生存！\n\n1. 收集资源维持生存\n2. 建造建筑提升效率\n3. 研究科技解锁新功能\n4. 管理背包优化存储',
        showCancel: false
      })
    },
    
    showGameControls() {
      uni.showModal({
        title: '操作说明',
        content: '• 点击TabBar切换不同功能\n• 点击物品查看详情\n• 长按建筑进行升级\n• 点击科技开始研究',
        showCancel: false
      })
    },
    
    // 获取游戏版本号（从manifest.json读取）
    getGameVersion() {
      try {
        // #ifdef APP-PLUS
        const manifest = require('@/manifest.json')
        return manifest.versionName || '1.0.0'
        // #endif
        
        // #ifdef H5
        // H5环境下，尝试从全局配置读取
        if (typeof window !== 'undefined' && window.__UNI_CONFIG__ && window.__UNI_CONFIG__.versionName) {
          return window.__UNI_CONFIG__.versionName
        }
        return '1.0.0'
        // #endif
        
        return '1.0.0'
      } catch (error) {
        console.error('获取游戏版本失败:', error)
        return '1.0.0'
      }
    },
    
    showAboutGame() {
      uni.showModal({
        title: '关于游戏',
        content: `荒岛生存 v${this.getGameVersion()}\n\n一款模拟荒岛生存的休闲游戏，体验在荒岛上收集资源、建造基地、研究科技的乐趣。`,
        showCancel: false
      })
    },
    
    showGameMenu() {
      // 显示游戏菜单
      uni.showActionSheet({
        itemList: ['游戏设置', '保存游戏', '读取游戏', '游戏帮助', '关于游戏'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              this.showGameSettings()
              break
            case 1:
              this.saveGame()
              break
            case 2:
              this.loadGame()
              break
            case 3:
              this.showGameHelp()
              break
            case 4:
              this.showAboutGame()
              break
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.survival-container {
  min-height: 100vh;
  background: #1a1a1a;
  color: white;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}


/* 主游戏区域 */
.main-game-area {
  flex: 1;
  display: flex;
  overflow: hidden;
  width: 100%;
  height: calc(100vh - 200rpx); /* 计算高度，减去头部高度 */
  background: transparent;
}






</style>
